#include "messageHandle.h"
#include <json-c/json.h>
#include "messageHandle.h"
#include "stdShared.h"
#include <unistd.h>
// 438


//构造函数
MessageHandle::MessageHandle(const StdTcpSocket &m_clientSocket):m_musicServer(m_clientSocket)
{
    m_handles[REGISTER]=[this](const std::string &data){m_musicServer.handleRegisterInfo(data);};
    m_handles[LOGIN]=[this](const std::string &data){m_musicServer.handleLogininInfo(data);};
    m_handles[DOWNLOAD_MUSIC]=[this](const std::string &data){m_musicServer.handleDownLoadMusic(data);};
     m_handles[SEARCH_MUSIC]=[this](const std::string &data){m_musicServer.handleSearchMusic(data);};
}



void MessageHandle::handleMessage(const std::string &data)
{
    // 解析 JSON 数据
    json_object *jsonObj = json_tokener_parse(data.c_str());
    if (jsonObj == NULL)
    {
        printf("JSON 解析失败\n");
    }
    else
    {
        int type = json_object_get_int(json_object_object_get(jsonObj, "type"));

        auto iter = m_handles.find(type);
        if(iter!=m_handles.end())
        {
            //执行回调函数
            iter->second(data);
        }else
        {
            //处理位置的消息类型
            std::cout<<"unknown message type"<<std::endl;
            m_clientSocket.sendMessage("unknown message type");
            
        }
        // 释放 JSON 对象
        json_object_put(jsonObj);
    }
}


